package com.vteba.utils.web.http;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultTrustManager implements X509TrustManager {
	private static final Logger LOGGER = LoggerFactory.getLogger(DefaultTrustManager.class);
	
	private TrustManager[] trustManagers;
	
	public static final DefaultTrustManager INS = new DefaultTrustManager();
	
	private DefaultTrustManager() {
		KeyStore keyStore = null;
		try {
			keyStore = KeyStore.getInstance("jks");
		} catch (KeyStoreException e) {
			LOGGER.error("获取jks类型KeyStore异常。", e.getMessage());
		}
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("conf/keystore.jks");
			keyStore.load(fis, "password".toCharArray());
		} catch (FileNotFoundException e) {
			LOGGER.error("没有获取到keystore.jks文件。", e.getMessage());
		} catch (NoSuchAlgorithmException e) {
			LOGGER.error("没有相应的算法异常。", e.getMessage());
		} catch (CertificateException e) {
			LOGGER.error("证书异常。", e.getMessage());
		} catch (IOException e) {
			LOGGER.error("IO异常。", e.getMessage());
		} finally {
			IOUtils.closeQuietly(fis);
		}
		
		TrustManagerFactory trustManagerFactory = null;
		try {
			trustManagerFactory = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
			trustManagerFactory.init(keyStore);
		} catch (NoSuchAlgorithmException e) {
			LOGGER.error("没有相应的算法异常。", e.getMessage());
		} catch (NoSuchProviderException e) {
			LOGGER.error("没有相应的算法提供者异常。", e.getMessage());
		} catch (KeyStoreException e) {
			LOGGER.error("获取KeyStore异常。", e.getMessage());
		}
		
		trustManagers = trustManagerFactory.getTrustManagers();
	}
	
	public TrustManager[] getTrustManagers() {
		return trustManagers;
	}
	
	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		// TODO Auto-generated method stub
		return null;
	}

}
